package com.itcp.itelpicture.manager.interceptor;

import com.itcp.itelpicture.constants.UserConstant;
import com.itcp.itelpicture.domain.po.User;
import com.itcp.itelpicture.domain.vo.UserVO;
import com.itcp.itelpicture.service.IUserService;
import com.itcp.itelpicture.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用户信息拦截器
 * 在请求处理前将HttpSession中的用户信息存储到ThreadLocal中
 * 在请求处理后清除ThreadLocal中的用户信息，避免内存泄漏
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class UserInfoInterceptor implements HandlerInterceptor {

    private final IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 从HttpSession中获取用户信息
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute(UserConstant.USER_LOGIN_STATE);

        // 如果用户已登录，则将用户信息存储到ThreadLocal中
        if (userObj != null && userObj instanceof User) {
            User user = (User) userObj;
            UserVO userVO = userService.getUserVO(user);
            UserHolder.saveUser(userVO);
            log.debug("UserInfoInterceptor: User [{}] info saved to ThreadLocal", user.getUserName());
        }

        // 无论用户是否登录，都继续执行后续请求处理
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // 请求处理完成后的操作，这里不做特殊处理
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // 请求完成后（包括视图渲染完成或发生异常），清除ThreadLocal中的用户信息，避免内存泄漏
        UserHolder.removeUser();
        log.debug("UserInfoInterceptor: User info cleared from ThreadLocal");
    }
}